import { defineStore } from 'pinia';
import { store } from '/@/store';
import { TOKEN_KEY } from '/@/enums/cacheEnum';
import { loginApi } from '@/api/login';
import { getConfigApi } from '@/api/index';

interface UserState {
  token?: string;
  config: Nullable<Recordable>;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // token
    token: undefined,
    config: null,
  }),
  getters: {
    getToken(state): string {
      return state.token || uni.getStorageSync(TOKEN_KEY);
    },
    getConfig(state): any {
      return state.config;
    },
  },
  actions: {
    setToken(token: string | undefined) {
      this.token = token ? token : '';
      uni.setStorageSync(TOKEN_KEY, token);
    },
    setConfig(config) {
      this.config = config;
    },

    async login(params) {
      try {
        const data = await loginApi(params);
        const { token } = data;

        // save token
        this.setToken(token);
        uni
          .switchTab({
            url: '/',
          })
          .then(() => {
            uni.showToast({
              title: '登录成功',
              icon: 'none',
            });

            this.setConfigAction();
          });
        return data;
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async logout() {
      this.setToken(undefined);

      uni
        .navigateTo({
          url: '/pages/login/index',
        })
        .then(() => {
          uni.showToast({
            title: '退出成功',
            icon: 'none',
          });
        });
    },
    async setConfigAction() {
      const data = await getConfigApi();
      this.setConfig(data);
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
